﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Web;
using System.Web.Mvc;
using Shamrock.Helpers;
using Shamrock.Models;

namespace Shamrock.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        ShamrockDataContext _messageDb = new ShamrockDataContext();

        public ActionResult Index(int? page)
        {
            const int pageSize = 7;
            var messages = from message in _messageDb.Messages
                           where message.ParentID.Equals(null)
                           orderby message.ReplyDate descending 
                           select message;
            var paginatedMessages = new PaginatedList<Message>(messages, page ?? 0, pageSize);

            ViewData["NewMessage"] = new Message();

            return View(paginatedMessages);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Index(Message message)
        {
            try
            {
                //logs
                _messageDb.Log = new DebugTextWriter();

                PostMessage(message);
                _messageDb.SubmitChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        private void PostMessage(Message message)
        {
            foreach (string file in Request.Files)
            {
                HttpPostedFileBase hpf = Request.Files[file];
                if (hpf.ContentLength == 0)
                    continue;
                if (!ImageProcessor.ValidateContentType(hpf.ContentType))
                {
                    continue;
                }

                string fileName = ImageProcessor.CreateFileName(hpf);
                string path;
                do
                {
                    path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "src", fileName);
                } while (System.IO.File.Exists(path));
                hpf.SaveAs(path);
                hpf.InputStream.Seek(0, SeekOrigin.Begin);
                string thumbnailPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "thumb",
                                                    fileName.Replace(".", "s."));

                using(var bitmap = (System.Drawing.Bitmap) System.Drawing.Image.FromStream(hpf.InputStream, true, true))
                {
                    var dimension = ImageProcessor.SaveThumbnail(bitmap, thumbnailPath, 250, 250);

                    message.HasImage = true;
                    var fileSplit = fileName.Split(new char[] { '.' }, 2);
                    message.Image = new Image()
                                        {
                                            FileTimestamp = fileSplit[0],
                                            Extension = fileSplit[1],
                                            FilePath = String.Format("~/src/{0}", fileName),
                                            ThumbPath = String.Format("~/thumb/{0}", fileName.Replace(".", "s.")),
                                            Size = hpf.ContentLength,
                                            Width = bitmap.Width,
                                            Height = bitmap.Height,
                                            ThumbWidth = dimension.X,
                                            ThumbHeight = dimension.Y,
                                        };
                }
            }
            if(message.Map.Address == null)
            {
                message.Map = null;
            }
            else
            {
                message.HasMap = true;
            }
            message.PostDate = DateTime.Now;
            message.ReplyDate = DateTime.Now;

            _messageDb.Messages.InsertOnSubmit(message);
        }

        public ActionResult Reply(int? id, int? page, bool showAll=false)
        {
            const int pageSize = 3;

            var messages = from message in _messageDb.Messages
                           where message.ParentID == id
                           orderby message.PostDate
                           select message;
            
            var paginatedMessages = new PaginatedList<Message>(messages, page, pageSize, showAll);

            ViewData["NewMessage"] = new Message() {ParentID = id};

            ViewData["ThreadPost"] = (from message in _messageDb.Messages
                                      where message.MessageID == id
                                      select message).Single();

            return View(paginatedMessages);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Reply(Message message)
        {
            try
            {
                var threadPost = (from thread in _messageDb.Messages
                                      where thread.MessageID == message.ParentID
                                      select thread).Single();
                threadPost.ReplyDate = DateTime.Now;

                PostMessage(message);
                _messageDb.SubmitChanges();

                return RedirectToAction("Reply", new {id = message.ParentID});
            }
            catch
            {
                return View();
            }
        }
        public ActionResult About()
        {
            return View();
        }
    }
}
